<template>
  <div>
    <el-tree
      ref="treeDate"
      :data="permissionList"
      default-expand-all
      :props="{label:'name'}"
      show-checkbox
      check-strictly
      node-key="id"
    />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>

  </div>
</template>

<script>
// 导入Api
import { getPermissionList } from '@/api/permission'
import { editRole, assignPerm } from '@/api/setting'
// 导入转换树形数据结构方法
import { transListToTree } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }

  },
  data() {
    return {
      permissionList: [] // 权限列表数据
    }
  },
  created() {
    // 调用获取权限列表方法
    this.getPermissionList()
    // 调用获取角色详情方法
    this.getRoleId()
  },
  methods: {
    // 获取权限列表
    async  getPermissionList() {
      const res = await getPermissionList()

      // 将数据转换树形结构

      this.permissionList = transListToTree(res.data, '0')
    },
    // 获取角色详情
    async getRoleId() {
      const res = await editRole(this.roleId)
      this.$refs.treeDate.setCheckedKeys(res.data.permIds)
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },
    // 确定权限按钮
    async setRolesBtn() {
      // 获取选中项
      const permIds = this.$refs.treeDate.getCheckedKeys()
      // 调用接口
      const res = await assignPerm({ id: this.roleId, permIds })
      // 用户提示
      this.$message.success(res.message)
      // 关闭弹窗
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
